<template>
	<div class="common-layout">
		<el-container class="h-screen">
			<!-- 头部 -->
			<el-header style="display: flex; align-items: center; justify-content: space-between;">
				<!-- 左侧：返回按钮 + 标题 -->
				<div class="header-left flex items-center">
					<!-- 标题 -->
					<el-text class="mx-1" style="font-size: 2em; color: #2A5D5B; font-weight: bold;">
						茗控中心
					</el-text>
					<!-- 返回按钮 -->
					<el-button link @click="onBack" class="back_btn">
						<el-icon>
							<ArrowLeft />
						</el-icon>
						<span>返回</span>
					</el-button>
				</div>
				<!-- 右侧：用户信息 + 退出按钮 -->
				<div class="header-right flex items-center">
					<!-- 用户信息 -->
					<div class="user-info flex items-center" style="margin-right: 20px;">
						<el-avatar :size="32" :src="userinfo.avatar" class="mr-3" />
						<el-popover title="电话号码" :content="userinfo.phone" placement="bottom">
							<template #reference>
								<span class="text-large font-600 mr-3 truncate-text"
									style="max-width: 150px; display: inline-block; vertical-align: middle; margin-bottom: 3px;">
									{{ userinfo.nickname }}
								</span>
							</template>
						</el-popover>
						<el-tag>{{userinfo.roleName}}</el-tag>
					</div>

					<!-- 退出按钮 -->
					<el-button type="primary" @click="showLogoutConfirm">退出登录</el-button>
				</div>
			</el-header>

			<el-container>
				<!-- 侧边栏 -->
				<el-menu router :default-active="$route.path" default-active="2" class="el-menu-vertical-demo"
					:collapse="isCollapse" style="height: calc(100vh - 84px); overflow-y: auto;">
					<!-- 箭头（收起展开按钮） -->
					<el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
						<el-radio-button :value="false" v-if="isCollapse"><el-icon>
								<ArrowRightBold />
							</el-icon></el-radio-button>
						<el-radio-button :value="true" v-else><el-icon>
								<ArrowLeftBold />
							</el-icon></el-radio-button>
					</el-radio-group>

					<!-- 侧边栏内容 -->
					<template v-for="item in navItems" :key="item.path">
						<!-- 有子菜单的情况 -->
						<el-sub-menu v-if="item.children" :index="item.path">
							<template #title>
								<el-icon>
									<component :is="item.icon" />
								</el-icon>
								<span>{{ item.name }}</span>
							</template>
							<template v-for="child in item.children" :key="child.path">
								<el-menu-item v-if="!child.hideInMenu" :index="child.path"
									@click="handleMenuItemClick(child)">
									<el-icon v-if="child.icon">
										<component :is="child.icon" />
									</el-icon>
									<span>{{ child.name }}</span>
								</el-menu-item>
							</template>
						</el-sub-menu>
						<!-- 有子菜单的情况 end-->

						<!-- 没有子菜单的情况 -->
						<el-menu-item v-else :index="item.path" @click="handleMenuItemClick(item)">
							<el-icon>
								<component :is="item.icon" />
							</el-icon>
							<span>{{ item.name }}</span>
						</el-menu-item>
						<!-- 没有子菜单的情况 end-->
					</template>
					<!-- 侧边栏内容 end-->
				</el-menu>
				<!-- 侧边栏 end-->
				<!-- 显示区 -->
				<el-main class="p-6" style="height: calc(100vh - 84px); display: flex;">
					<!-- 标签页 -->
					<div style="flex: 1; min-height: 0; overflow-y: auto">
						<el-tabs v-model="editableTabsValue" type="card" editable class="demo-tabs"
							@edit="handleTabsEdit" @tab-click="handleTabClick">
							<el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title"
								:name="item.name" :closable="!item.fixed">
								<router-view v-if="editableTabsValue === item.name" :key="route.fullPath"></router-view>
							</el-tab-pane>
						</el-tabs>
					</div>
				</el-main>
			</el-container>
		</el-container>

		<el-dialog v-model="logoutDialogVisible" title="确认退出" width="400px">
			<span>确定要退出当前账号吗？</span>
			<template #footer>
				<el-button @click="logoutDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleLogoutThenRedirect"
					class="!bg-[#2A5D5B] hover:!bg-[#1d4947] !text-white">
					确定
				</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import navItems from '@/config/navItems.js';
	import {
		useTabsStore
	} from '@/store/tabs'

	import {
		removeToken,
		getToken
	} from '@/utils/token.js'

	import {
		getLocalUserinfo,
		setLocalUserinfo,
		removeLocalUserinfo
	} from '@/utils/userinfo.js'

	import {
		getUserinfo
	} from '@/api/user.js'

	import {
		ref,
		onMounted,
		nextTick,
		watch,
		computed
	} from 'vue'

	import {
		User,
		ArrowLeftBold,
		ArrowRightBold,
		Menu,
		ArrowLeft
	} from '@element-plus/icons-vue'

	import {
		ElNotification as notify
	} from 'element-plus'

	import {
		useRouter,
		useRoute
	} from 'vue-router'
	/**
	 * 缓存标签实例
	 */
	const tabsStore = useTabsStore()
	/**
	 * router实例
	 */
	const router = useRouter()
	/**
	 * route实例
	 */
	const route = useRoute()
	/**
	 * 收起展开按钮用
	 */
	const isCollapse = ref(false)
	/**
	 * 存储用户信息
	 */
	const userinfo = ref({})

	// 标签页相关
	const tabIndex = computed(() => tabsStore.tabIndex)
	const editableTabsValue = computed({
		get: () => tabsStore.activeTab,
		set: (val) => {
			tabsStore.activeTab = val
		}
	})
	/**
	 * 初始标签页设置
	 */
	const editableTabs = computed(() => tabsStore.tabs)
	/**
	 * 初始化标签页
	 */
	const initTabs = () => {
		tabsStore.initFromRoute(route)
	}

	/**
	 * 添加标签页
	 */
	const addTab = (route) => {
		if (this.tabs.length >= 10) { // 限制最多10个标签页
			ElMessage.warning('标签页数量已达上限，请先关闭一些标签页')
			return
		}
		tabsStore.addTab(route)
	}

	/**
	 * 处理标签页编辑
	 */
	const handleTabsEdit = async (targetName, action) => {
		if (action === 'remove') {
			// 暂时注释
			// try {
			// 	await ElMessageBox.confirm('确定要关闭这个标签页吗？', '提示', {
			// 		type: 'warning'
			// 	})
			const pathToNavigate = tabsStore.removeTab(targetName)
			if (pathToNavigate) {
				router.push(pathToNavigate)
			}
			// } catch (error) {
			// 	console.log('取消关闭标签页')
			// }
		}
	}

	/**
	 * 处理标签页点击
	 */
	const handleTabClick = (tab) => {
		const tabName = tab.paneName
		const selectedTab = tabsStore.tabs.find(t => t.name === tabName)
		if (selectedTab) {
			router.push(selectedTab.path)
		}
	}

	/**
	 * 处理菜单项点击
	 */
	const handleMenuItemClick = (menuItem) => {
		router.push(menuItem.path)
	}

	// 监听路由变化
	watch(() => route, (newRoute) => {
		// 跳过首页路由的标题更新
		if (newRoute.path === '/home') return

		if (newRoute.meta?.tab) {
			tabsStore.addTab(newRoute)
		}
	}, {
		deep: true,
		immediate: true // 确保初始化时执行
	})

	/**
	 * 获取并保存用户信息
	 */
	const setUserinfoFunc = async () => {
		try {
			const res = await getUserinfo();
			if (res?.data) {
				setLocalUserinfo(res.data);
				userinfo.value = res.data;
			}
		} catch (e) {
			console.error('获取用户信息失败:', e);
			// 可选：读取本地旧数据作为降级
			userinfo.value = getLocalUserinfo() || {
				id: '',
				nickname: ''
			};
		}
	};

	onMounted(async () => {
		initTabs();
		await setUserinfoFunc(); // 单次操作
	});

	/**
	 * 回退到上一页
	 */
	const onBack = () => {
		router.back(-1)
	}

	const activeNav = ref('课程管理')
	const logoutDialogVisible = ref(false)
	const updateTime = ref(new Date().toLocaleTimeString('zh-CN', {
		hour: '2-digit',
		minute: '2-digit'
	}))

	const courseChart = ref(null)
	const roomChart = ref(null)

	const handleMenuSelect = (index) => {
		activeNav.value = index
	}

	/**
	 * 显示退出登录弹窗
	 */
	const showLogoutConfirm = () => {
		logoutDialogVisible.value = true
	}

	/**
	 * 退出登录逻辑
	 */
	const handleLogoutThenRedirect = () => {
		logoutDialogVisible.value = false
		//删除本地token
		removeToken()
		const token = getToken()
		if (!token) {
			// 跳转登录页
			router.push('/login')
			//删除本地的用户信息
			removeLocalUserinfo()
			//删除标签页缓存
			localStorage.removeItem("tabs");
		}
	}
</script>

<style scoped>
	.header-left {
		display: flex;
		align-items: center;
	}

	.header-right {
		display: flex;
		align-items: center;
	}

	.user-info {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.truncate-text {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 150px;
	}


	:deep(.el-page-header__extra) {
		order: 2;
	}

	.el-menu-vertical-demo:not(.el-menu--collapse) {
		width: 200px;
		min-height: 400px;
	}

	.el-radio-group {
		display: flex;
		/* 反转内部元素顺序 */
		flex-direction: row-reverse;
	}

	:deep(.el-radio-button__inner) {
		border: none !important;
		background-color: transparent !important;
	}

	.back_btn {
		margin-left: 3.125rem;
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 0;
		font-size: 1em;
		color: #606266;
		transition: color 0.3s;
	}

	.el-main {
		display: flex;
		flex-direction: column;
		overflow: auto;
	}

	.nav-link {
		text-decoration: none !important;
	}

	.nav-link.active {
		color: white;
	}

	.nav-link:not(.active) {
		color: #666;
	}

	/* 标签页 */
	.demo-tabs {
		height: calc(100vh - 60px);
		/* 减去头部高度 */
		display: flex;
	}

	.demo-tabs :deep(.el-tabs__content) {
		flex: 1;
		overflow: hidden;
	}

	.demo-tabs :deep(.el-tab-pane) {
		height: 100%;
	}

	.el-tabs__content {
		transition: all 0.3s ease;
	}

	/* 滚动条样式 */
	.el-menu-vertical-demo::-webkit-scrollbar {
		width: 6px;
	}

	.el-menu-vertical-demo::-webkit-scrollbar-thumb {
		background-color: #c1c1c1;
		border-radius: 3px;
	}

	.el-menu-vertical-demo::-webkit-scrollbar-track {
		background-color: #f1f1f1;
	}
</style>